package com.baseframe.advert.controller;

import com.baseframe.advert.entity.SnsAdvert;
import com.baseframe.advert.entity.request.SnsAdvertRequest;
import com.baseframe.advert.service.SnsAdvertService;
import com.baseframe.advert.sign.AdvertType;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.BaseMetaObjectUtil;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.tool.container.Kv;
import com.baseframe.tool.result.R;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/back/advert")
@AllArgsConstructor
public class BackSnsAdvertController {

    private SnsAdvertService snsAdvertService;

    /**
     * 新增或修改广告
     *
     * @param request 请求对象，包含广告信息
     * @return 返回操作结果
     */
    @PostMapping("/save-or-update")
    public R<Object> addAdvert(@RequestBody SnsAdvertRequest request) {
        SnsAdvert snsAdvert = new SnsAdvert();
        BeanUtils.copyProperties(request, snsAdvert,
                BaseMetaObjectUtil.getUpdateFillPropertiesName(snsAdvert.getClass()));

        snsAdvert.setPublisher(AuthUtil.getUserId());

        return snsAdvertService.saveOrUpdate(snsAdvert) ? R.success() : R.fail();
    }

    /**
     * 分页查询广告
     *
     * @param pageInfo 分页信息对象
     * @param request  请求对象，包含查询条件
     * @return 返回查询结果
     */
    @GetMapping("/page")
    public R<Object> advertPage(PageInfo pageInfo, SnsAdvertRequest request) {
        return R.data(snsAdvertService.advertPage(pageInfo, request));
    }

    /**
     * 删除广告
     *
     * @param request 请求对象，包含广告ID
     * @return 返回操作结果
     */
    @PostMapping("/delete")
    public R<Object> deleteAdvert(@RequestBody SnsAdvertRequest request) {
        if (request.getId() == null) {
            return R.fail("缺少必要请求参数~");
        }
        return snsAdvertService.removeById(request.getId()) ? R.success() : R.fail();
    }

    /**
     * 获取广告类型列表
     *
     * @return 返回广告类型列表
     */
    @GetMapping("/type/list")
    public R<List<Kv>> getAdvertTypes() {
        List<Kv> advertTypeList = new ArrayList<>();

        // 遍历广告类型枚举，构建广告类型列表
        for (AdvertType value : AdvertType.values()) {
            Kv advertMap = Kv.create();
            advertMap.put("type", value.getCode());
            advertMap.put("name", value.getName());

            advertTypeList.add(advertMap);
        }
        return R.data(advertTypeList);
    }
}
